<template>
  <div class="newUsers">
    <div class="aroundOf" v-if="this.$route.params.add === 'add'">新增用户</div>
    <div class="aroundOf" v-else-if="this.$route.params.add === 'newAdd'">添加学生管理</div>
    <div class="aroundOf" v-else>编辑用户</div>
    <div class="resourcese">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="单个新增" name="1">
          <div class="attribute_o">
            <p>用户属性：</p>
            <el-button @click="userAttributes(ind)" v-for="(item, ind) in user" :key="ind" :class="index == ind ? 'activeClass' : ' '">{{ item.name }}</el-button>
          </div>
          <!-- 个人用户 -->
          <el-form
            :model="ruleForms"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
            v-if="index == 0"
          >
            <!-- <el-form-item
              label="用户名："
              style="width: 100%; text-align: left" >
              <el-input v-model="ruleForms.username" placeholder="请输入8-20个字符的用户名" maxlength="20" show-word-limit @change="userLegal"></el-input>
            </el-form-item> -->
            <el-form-item
              label="手机号："
              style="width: 96%; text-align: left"
            > 
              <el-input
                v-model.number="ruleForms.mobilePhone"
                maxlength="11"
                placeholder="请输入您的11位数字的手机号"
                show-word-limit
                @input="imageTextInputChange"
              ></el-input>
            </el-form-item>
            <el-form-item label="验证码：" style="width: 100%; text-align: left;" class="label_input">
              <el-input v-model.trim="ruleForms.verification" maxlength="6" placeholder="请输入6位数字的验证码" oninput="value = value.replace(/[^\d]/g,'')" style="width: 75%"></el-input>
              <el-button type="primary" class="code" v-show="show" @click.prevent="VerificationCode()">获取验证码</el-button>
              <el-button type="primary" class="code" v-show="!show">{{ count }}s后重试</el-button>
            </el-form-item>
            <el-form-item class="addStudents">
              <el-button type="primary" @click="submitForm()">添加学生</el-button>
            </el-form-item>
          </el-form>
          <!-- 机构用户 -->
          <!-- <el-form :model="ruleFormsE" ref="ruleFormAs" label-width="100px" class="demo-ruleForm" v-else>
            <el-form-item label="用户机构：" style="width: 70%; text-align: left">
              <el-select v-model="ruleFormsE.region" filterable placeholder="请选择用户机构" style="width: 53%">
                <el-option v-for="(item, index) in forName" :key="index" :label="item.iname" :value="item.iname"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="真实姓名：" style="width: 40%; text-align: left">
              <el-input v-model="ruleFormsE.name" placeholder="请输入真实姓名"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForms()">添加学生</el-button>
            </el-form-item>
          </el-form> -->
        </el-tab-pane>

        <!-- <el-tab-pane label="批量新增" name="2">
          <div class="container download">
            <div class="row downloadsEa">
              <div class="col col-xxl-6 col-lg-12 col-xl-6">
                <div class="download_l">
                  <h1>1.模板下载</h1>
                  <p>
                    请先下载模板，并按照模板格式完成数据填写，填写候在右侧完成数据导入
                  </p>
                  <el-button type="primary" @click="download" class="download_btn">下载模板</el-button>
                  <h1>2.数据导入</h1>
                  <p>按页面提示，将数据表格拖入下方，导入数据</p>
                  <div class="intoThe">
                    <p>上传文件：</p>
                    <el-upload
                      class="upload-demo"
                      drag
                      ref="upload"
                      :file-list="fileList"
                      :action=" baseUrl + '/StudentUser/import'"
                      :before-upload="beforeUploadFile"
                      :on-success="onSuccess"
                      :on-remove="onRemove"
                      multiple
                      :auto-upload="false"
                        accept=".xls"
                      :limit="1">
                      <i class="el-icon-upload"></i>
                      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    </el-upload>
                  </div>
                  <el-button type="primary" style="width: 120px;margin: 10px;" @click="submitUpload">导入</el-button>
                </div>
              </div>
              <div class="col col-xxl-6 col-lg-12 col-xl-6">
                文件上传成功后展示
                <div class="download_r">
                  <h1>3.数据确认</h1>
                  <el-button @click="deletEe" class="deletEe">删除</el-button>
                  <el-table v-if="disappear" :data="gridData" style="width: 100%;margin-top: 66px;" max-height="250" :header-cell-style="{ background: '#f2f2f2', color: '#333', fontWeight: 600, }">
                    <el-table-column label="姓名" align="center"> 
                      <template slot-scope="scope"> <span class="scope_span1">• {{ scope.row.name == '' ? '--' : scope.row.name }}</span> </template>
                    </el-table-column>
                    <el-table-column label="绑定手机号" align="center">
                      <template slot-scope="scope"> {{ scope.row.phone == '' ? '--' : scope.row.phone }} </template>
                    </el-table-column>
                    <el-table-column label="机构所属" align="center">
                      <template slot-scope="scope">
                        <span class="scope_span1">• {{ scope.row.iname == '' ? '--' : scope.row.iname }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" align="center">
                      <template slot-scope="scope"> <el-button @click.native.prevent="deleteRow(scope.$index, gridData)" type="text" size="small" > 删除 </el-button> </template>
                    </el-table-column>
                  </el-table>
                  <div class="bacth">
                    <el-button type="primary" @click="batchAdd" class="batchAdd">批量添加学生</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </el-tab-pane> -->
      
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { base } from '../../api/axiosFun';
export default {
  data() {
    return {
      baseUrl: '',
      activeName: '1',
      isShow: true, //控制切换显示
      show: 'false',
      disappear: true,
      count: '', //多少秒之后结束
      tabss: 'institutions', //同上
      index: 0,
      // { name: '机构用户' }, 
      user: [{ name: '个人用户' }],
      ruleForms: {
        username: '', //用户名
        mobilePhone: '', //手机号
        verification: '' //验证码
      },
      ruleFormsE: {
        name: '', //真实姓名
        region: '' //用户机构
      },
      tabsName: '', //当前点击的用户属性
      forName: [],
      newAddcan: '',
      nameDisalong: '', //  展示的名称
      gridData: [],  // 上传成功后展示的数据
      fileList: [],  // 导入的文件
      newExtension: '',
    };
  },
  mounted() {
    this.baseUrl = base;
    this.newAddcan = this.$route.params.add;
    if (this.$route.params.add === 'add') {
      this.institutionsDropDown()
    } else {
      this.index = this.$route.params.type = 0;
      this.ruleForms.username = this.$route.params.name;
      this.ruleForms.mobilePhone = this.$route.params.phone;
      this.institutionsDropDown();
    }
  },
  methods: {
    institutionsDropDown() {  // 这个是机构用户中的 获取机构下拉框
      this.$http.theUser.addUserMaGou().then(res => {
        this.forName = res.data;
      })
    },
    // 这个是单个和批量切换 目前没有用到
    handleClick(tab, event) {
      console.log(tab, event)
    },
    // 这个是用户属性的切换
    userAttributes(index) {
      this.index = index
      this.show = true
      this.ruleForms = {
        username: '', //用户名
        mobilePhone: '', //手机号
        verification: '' //验证码
      }
      this.ruleFormsE = {
        name: '', //真实姓名
        region: '' //用户机构
      }
    },
    imageTextInputChange(val) {  // 校验手机号
      this.ruleForms.mobilePhone = val;
    },
    // 发送验证码
    VerificationCode() {// console.log(this.ruleForms.mobilePhone.length)
      if(this.ruleForms.mobilePhone != '' && this.ruleForms.mobilePhone.length === 11) {
        let params = { phone: this.ruleForms.mobilePhone };
        var reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
        if(reg.test(params.phone)) {
          this.ruleForms.mobilePhone = params.phone;// 发送验证码接口
          this.$http.theUser.addUserMa(params).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '发送验证码成功，请注意查收',
                type: 'success'
              })
              this.theCountdown();
            }
          })
        } else {
          this.$message({
            message: '请输入正确的手机号码',
            type: 'error'
          })
        }
      } else {
        this.$message({
          message: '警告，手机号不能为空或请正确输入11位手机号',
          type: 'warning'
        });
      }
    },
    // 判断手机号是否合法
    validatePhone() {
      if (!this.ruleForms.mobilePhone) {
        this.$message({
          message: '手机号码不能为空',
          type: 'error'
        })
      } else if (!/^1[3|4|5|7|8][0-9]\d{8}$/.test(this.ruleForms.mobilePhone)) {
        this.$message({
          message: '请输入正确是手机号',
          type: 'error'
        })
      } else {
        return true
      }
    },
    // 验证码倒计时
    theCountdown() {
      this.count = 60
      this.show = false
      let timer = 0
      timer = setInterval(() => {
        if (this.count > 0 && this.count <= 60) {
          this.count--
        } else {
          this.show = true
          clearInterval(timer)
          timer = 0
        }
      }, 1000)
    },
    // 判断用户名是否合法
    userLegal(val){// console.log(val)
      const idNumberReg = /[^[0-9a-zA-Z_\u3E00-\u9FA5]{8,20}$]|[^\d]/;
      if(idNumberReg.test(val)) {
        return false;
      } else {
        this.$message({
          message: '您的用户名仅支持中英文、数字和下划线,且不能为纯数字!',
          type: 'warning'
        });
        this.ruleForms.username = '';
      }
    },
    // 校验保存按钮
    submitForm() {
      // this.$route.params.add == 'newAdd' console.log(this.$route.params.add) // this.ruleForms.username == '' || name: this.ruleForms.username,this.ruleForms.username == '' || 这个是用户列表新增过来的
      if (this.$route.params.add == 'add') {
        if (this.ruleForms.mobilePhone == '' || this.ruleForms.verification == '') {
          this.$message({
            message: '警告哦，个人用户存在未填写内容，请填写',
            type: 'warning'
          })
        } else{
          this.$http.theUser.addUser({ phone: this.ruleForms.mobilePhone,type: 2,code: this.ruleForms.verification})
          .then(res => {
            if (res.code == 0) {
              this.$message({
                message: '成功创建个人用户',
                type: 'success'
              })
              this.$router.push({ path: '/theUser' })
            }
          })
        }
      } else {// 这个是用户详情中编辑过来的 ，进行编辑修改个人信息
        if (this.ruleForms.mobilePhone == '' || this.ruleForms.verification == '') {
          this.$message({
            message: '警告哦，个人用户存在未填写内容，请填写',
            type: 'warning'
          })
        } else {
          this.$http.theUser.addUser({ id: this.$route.params.id, name: this.ruleForms.username, phone: this.ruleForms.mobilePhone, type: 2,       code: this.ruleForms.verification }).then(res => {
            if (res.code == 0) {
              this.$message({
                message: '成功修改个人用户',
                type: 'success'
              })
              this.$router.push({ path: '/theUser' })
            }
          })
        }
      }
    },
    // 暂时先不要下面这个
    // submitForms() {
    //   if (this.$route.params.add == 'newAdd') {
    //     if (this.ruleFormsE.name == '' || this.ruleFormsE.region == '') {
    //       this.$message({
    //         message: '警告哦，机构用户存在未填写内容，请填写',
    //         type: 'warning'
    //       })
    //     } else {
    //       // 机构添加
    //       this.$http.theUser.addUser({ iname: this.ruleFormsE.region, zhename: this.ruleFormsE.name, type: 1 }).then(result => {
    //         if (result == undefined) {
    //           this.$message({
    //             message: '成功创建个人用户',
    //             type: 'success'
    //           })
    //           this.$router.push({ path: '/institutions/agency' })
    //         }
    //       })
    //     }
    //   } else if (this.newAddcan === 'add') {
    //     if (this.ruleFormsE.name == '' || this.ruleFormsE.region == '') {
    //       this.$message({
    //         message: '警告哦，机构用户存在未填写内容，请填写',
    //         type: 'warning'
    //       })
    //     } else {
    //       // 机构添加
    //       this.$http.theUser.addUser({ iname: this.ruleFormsE.region, zhename: this.ruleFormsE.name, type: 1 }).then(result => {
    //         console.log(result)
    //         if (result.code == 200) {
    //           this.$message({
    //             message: '成功创建个人用户',
    //             type: 'success'
    //           })
    //           this.$router.push({ path: '/theUser' })
    //         }
    //       })
    //     }
    //   } else {
    //     if (this.ruleFormsE.name == '' || this.ruleFormsE.region == '') {
    //       this.$message({
    //         message: '警告哦，机构用户存在未填写内容，请填写',
    //         type: 'warning'
    //       })
    //     } else {
    //       // 这个是用户详情中编辑过来的 ，进行编辑修改机构信息
    //       this.$http.theUser
    //         .addUser({
    //           id: this.$route.params.id,
    //           iname: this.ruleFormsE.region,
    //           zhename: this.ruleFormsE.name,
    //           type: 1
    //         })
    //         .then(result => {
    //           console.log(result)
    //           if (result == undefined) {
    //             this.$message({
    //               message: '成功修改机构用户',
    //               type: 'success'
    //             })
    //             this.$router.push({ path: '/theUser' })
    //           }
    //         })
    //     }
    //   }
    // },

    // 批量新增操作
    //导入按钮
    

    // 
    

    submitUpload() {  // 这个是批量新增中的导入
      if(this.newExtension === 'xls'){
        this.$refs.upload.submit();
      } else {
        this.$message({
          message: '请上传以.xls结尾的文件',
          type: 'warning'
        });
        this.fileList = [];
      }
    },
    // 上传文件限制
    beforeUploadFile(file){
      console.log(file)
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      this.newExtension = extension;
      const size = file.size / 1024 / 1024;
      if (extension !== 'xls') {
        this.$notify.warning({
          title: '警告',
          message: `只能上传（即后缀是.xls）的文件`
        })
        this.fileList = []; //  如果不是.apk的文件就把这个数组给至空
      }
      // if (size > 500) {
      //   this.$notify.warning({
      //     title: '警告',
      //     message: `文件大小不得超过500M`
      //   })
      // }
    },
    // 上传成功后展示
    onSuccess(response, file, fileList){
      // console.log(response,file, fileList);
      if(response.code == 200 || response.code == 0 || response.code == 201){
        this.$message({
          message: '导入成功',
          type: 'success'
        });
        this.nameDisalong = file.name;
        this.gridData = response.data;
      } else if(response.code == 501) {
        this.fileList = [];
        this.$message({
          message: response.errorMessage,
          type: 'warning'
        });
      }
    },
    onRemove(file, fileList){
      if(fileList.length == 0) {
        this.gridData = [];
      }
    },
    // 下载模板addUserXia
    download() {
      this.$http.theUser.addUserXia().then(res => {
        const fileName = '下载的文件'
        // const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement('a');
        link.style.display = 'none';
        // console.log(process.env.NODE_ENV);
        if(process.env.NODE_ENV == 'development'){       // 开发环境
          link.href = 'http://192.168.1.146:9001/bzsz/StudentUser/Daochu';
        }else if(process.env.NODE_ENV == 'production'){  // 生产环境或者叫做线上的环境
          link.href = 'http://xuexi.bzszxr.com/bzsz/StudentUser/Daochu';
        }else {   // 测试环境http://admin-test.bzszxr.com/bzsz
          // link.href = 'http://test.bzszxr.com/bzsz/StudentUser/Daochu';
          link.href = 'http://admin-test.bzszxr.com/bzsz/StudentUser/Daochu';
        };
        link.setAttribute('download', fileName + '.xls');
        document.body.appendChild(link);
        link.click();
        // 下载完成移除元素
        document.body.removeChild(link)
        // 释放掉blob对象
        // window.URL.revokeObjectURL(url)
      })
    },
    // 右侧删除表格
    deletEe() {
      console.log('右侧删除表格')
      // this.disappear = false;
      this.gridData = [];
    },
    // 表格删除
    deleteRow(index, rows) {
      rows.splice(index, 1)
    },
    // 批量添加学生按钮
    batchAdd(){
      this.$http.theUser.importAdd({userStudentAdd: this.gridData}).then( res => {
        console.log(res)
      })
    }
  }
}
</script>

<style scoped>
@import '../../assets/css/theUser/newUsers.scss';
</style>
